package hpu.e4_demo.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import hpu.e4_demo.common.Result;
import hpu.e4_demo.entity.TUserInfo;
import hpu.e4_demo.entity.TUsers;
import hpu.e4_demo.mapper.TUserInfoMapper;
import hpu.e4_demo.mapper.TUsersMapper;
import hpu.e4_demo.service.ITUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import hpu.e4_demo.utils.JwtUtil;
import hpu.e4_demo.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 用户表（登录时查询） 服务实现类
 * </p>
 *
 * @author FFF
 * @since 2025-06-21
 */
@Service
public class TUsersServiceImpl extends ServiceImpl<TUsersMapper, TUsers> implements ITUsersService {
    @Autowired
    private TUsersMapper tUsersMapper;
    @Autowired
    private TUserInfoMapper tUserInfoMapper;

    @Override
    public Result<List<TUsers>> findAll() {
        return Result.ok(tUsersMapper.selectList(null));
    }

    @Override
    public  Result<String> add(TUsers tUsers) {
        tUsers.setRole("用户");
        Result<String> result = new Result<>();
        //密码加密
        tUsers.setPassword(MD5.getMD5String(tUsers.getPassword()));
        //同步用户信息表
        if (tUsersMapper.insert(tUsers) > 0){
            Random random = new Random();
            String idNumber;
            idNumber = String.valueOf(random.nextInt(1000000000));
            TUserInfo tUser = new TUserInfo();
            tUser.setUserName(tUsers.getUserName());
            tUser.setPassword(tUsers.getPassword());
            tUser.setCreateTime(LocalDateTime.now());
            tUser.setModifyTime(LocalDateTime.now());
            tUser.setUserIdNumber(idNumber);
            tUserInfoMapper.insert(tUser);
             result = Result.ok("注册成功");
        }else {
             result = Result.fail("注册失败，用户名已被占用");
        }
        return result;
    }

    @Override
    public Result<Map<String, Object>> login(String user_name, String password, String role) {
        password = MD5.getMD5String(password);
        QueryWrapper<TUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",user_name).eq("password",password);
        queryWrapper.eq("role",role);
        List<TUsers> result = tUsersMapper.selectList(queryWrapper);


        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        if (result.size() > 0){
            Map<String,Object> map = new HashMap<>();
            //result.get(0) 表示取查询结果中的第一个用户；
            map.put("id",result.get(0).getId());
            map.put("username",user_name);
            //1000*60*60 为1h   当前时间+****** 即为过期时间
            //withClaims() 添加载荷(用户信息) 这里为了安全才不加密码等信息.有效载荷反编码可以得到用户信息。
            //令牌创建、校验也可以封装成一个工具类
            String token = JwtUtil.creatToken(map);
            System.out.println(token);

            //验证jwt令牌，验证+解码
            /*JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("FYH666")).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            Map<String, Claim> claims = decodedJWT.getClaims();*/
            //此时claims中存放了用户信息，即有效载荷


            map1.put("state","登录成功");
            map1.put("token", token);
        } else {
            map2.put("state", "登录失败，用户名或密码错误");
        }
        return result.size() > 0 ? Result.ok(map1) : Result.fail(map2);

    }




}
